layui.use(['tableEdit', 'table', 'form', 'laydate',"selectInput","excel"], function () {
    let layer = layui.layer //弹层
        ,table = layui.table //表格
        ,form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        excel = layui.excel,
        selectInput = layui.selectInput;
    lay('.starttime').each(function(){
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem=[]
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=  getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }
    function getxmselect(el,name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon:true,
                indent: 20,
                expandedKeys:false
            },
            height: 'auto',
            data: data,
            on: function ({ arr, change, isAdd }) {
                return this
            }
        })
    }


    let collectTypeData = [];
    let billTypeData = [];
    let businessModelList = [];
    let operationList=[];
    let salesmanList=[];
    let pricetermList=[];
    let deptSalesmanList = [];
    let deptOperationList=[];
    (function () {
        let treeList = getCurrentDepartmentUser();
        if(treeList && treeList.list){
            let operationTree = getAllJson(treeList.list);
            operationList=getxmselect("#operationCode","operationCode", operationTree)
            salesmanList=getxmselect("#salesmanCode","salesmanCode", operationTree)
        }else {
            operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}])
            salesmanList= getxmselect("#salesmanCode","salesmanCode", [{name: user.name, value: user.code}])
        }

        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        } else {
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
        }

        //获取业务模式信息
        $.ajax({
            url: "offer/getBusinessModel",
            async: false,
            success: function (data) {
                if (data.status == 200) {
                    let businessModelData = [];
                    for (let i in data.data) {

                        if(data.data[i].name!="备货入库"){
                            let tmp = {
                                name: data.data[i].name,
                                value: data.data[i].name
                            }
                            businessModelData.push(tmp);
                        }

                    }
                    businessModelList = getxmselect("#businessMode", "businessMode", businessModelData);
                    form.render('select');
                }
            }
        });

        //收款类型
        let isDone = [
            {name: "收款完成", value: "1"},
            // {name: "未收款", value: "2"},
            // {name: "部分收款", value: "3"},
            {name: "收款未完成", value: "3"},
        ];
        collectTypeData = getxmselect("#isDone", "isDone", isDone);


        //单据信息
        let billNoStatus = [
            {name: "草稿箱", value: "1"},
            {name: "待批箱", value: "2"},
            {name: "已批箱", value: "3"},
            {name: "完成箱", value: "4"},
            {name: "垃圾箱", value: "5"}
        ];
        billTypeData = getxmselect("#status", "status", billNoStatus);

        //获取币种
        $.ajax({
            url:"receivePayment/getCurrencyInfo",
            success:function(data){
                if(data.status == 200){
                    for(let i in data.data){
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].name));
                    }
                    form.render('select');
                }
            }
        });

        //价格术语
        var priceterm=getdictionary(5,16);
        let pricetermTree = getAllJsonPrice(priceterm);
        pricetermList=getxmselect("#priceTerms","priceTerms", pricetermTree)

    })()

    function getAllJsonPrice(jsons) {
        let tempArr=[];
        for (let item of jsons) {
            let temp={}
            temp["value"]=item["name"];
            temp["name"]=item["name"];

            tempArr.push(temp);
        }
        return tempArr;
    }


    form.render();//表单刷新
    let initData = [];
    table.render({
        elem: '#collection2Select'
        ,data:initData
        ,toolbar: '#collection2Toolbar'
        ,totalRow: true
        ,cols: [[
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            , {field: 'invoiceStr', title: '发票日期', sort: true, width: 120, align: 'center'}
            , {field: 'customerSource', title: '客户来源', sort: true, width: 120, align: 'center'}
            , {field:'priceTermsName', title:'结汇价格术语',sort:true,width: 120, align: 'center'}
            , {field:'ecPriceName', title:'外销价格术语',sort:true,width: 120, align: 'center'}
            , {field: 'customerCode', title: '客户编码', sort: true, width: 120, align: 'center'}
            , {field: 'customerName', title: '客户名称', sort: true, width: 120, align: 'center'}
            , {field: 'billExchangeSalesman', title: '业务员', sort: true, width: 120, align: 'center'}
            , {field: 'invoiceNumber', title: '发票编号', sort: true, width: 200, align: 'center',event:'invoiceNumber'}
            , {field:'contractNo', title:'外销合同号',sort:true,width: 120, align: 'center'}
            , {field:'currencyEnglishName', title:'币种',sort:true,width: 120, align: 'center'}
            , {field:'invoiceMoney', title:'应收货款',sort:true,width: 120, align: 'center', totalRow: true}
            , {field:'invoiceMoneyUsd', title:'应收货款(USD)',sort:true,width: 160, align: 'center', totalRow: true}
            , {field:'invoiceMoneyRmb', title:'应收货款(RMB)',sort:true,width: 160, align: 'center', totalRow: true}
            , {field:'collectionAmount', title:'已收货款',sort:true,width: 120,event: "collectionAmount", align: 'center', totalRow: true}
            , {field: 'unPayment', title: '未收货款', sort: true, width: 120, align: 'center', totalRow: true}
            , {field: 'unPaymentRmb', title: '未收货款(RMB)', sort: true, width: 120, align: 'center', totalRow: true}
            , {field: 'amountClaimed', title: '实收货款', sort: true, width: 120, align: 'center', totalRow: true}
            , {field:'collectionAmountRmb', title:'人民币已收',sort:true,width: 120, align: 'center', totalRow: true}
            , {field: 'amountClaimedRmb', title: '人民币实收', sort: true, width: 120, align: 'center', totalRow: true}
            , {field: 'billExchangeOperatorName', title: '操作员', sort: true, width: 120, align: 'center'}
            , {field: 'maxClaimDateStr', title: '最近一次认领日期', sort: true, width: 200, align: 'center'}
            , {field: 'billExchangeCompanyName', title: '公司', sort: true, width: 200, align: 'center'}
            , {field: 'billExchangeBankName', title: '银行名称', sort: true, width: 200, align: 'center'}
            , {field: 'receivablePayday', title: '应收到账日期', sort: true, width: 120, align: 'center'}
            , {field: 'payday', title: '账期', sort: true, width: 120, align: 'center'}
            , {field: 'advanceCollectionDay', title: '提前收款天数', sort: true, width: 250, align: 'center'}
            , {field: 'overdue', title: '逾期', sort: true, width: 250, align: 'center'}
            , {field: 'endPlace', title: '运抵国', sort: true, width: 120, align: 'center'}
            , {field: 'actualAtdStr', title: '实际开船日期', sort: true, width: 120, align: 'center'}
            , {field: 'businessMode', title: '业务模式', sort: true, width: 120, align: 'center'}
            , {field: 'foreignBankDeductions', title: '国外银行扣费（原币）', sort: true, width: 120, align: 'center', totalRow: true}
            , {field: 'domesticBankCharge', title: '国内银行扣费', sort: true, width: 120, align: 'center', totalRow: true}
            , {field: 'refundAmount', title: '退款金额', sort: true, width: 120, align: 'center', totalRow: true}
            , {field: 'refundAmountRmb', title: '人民币退款金额', sort: true, width: 120, align: 'center', totalRow: true}

        ]]
        ,id: 'maininformationtableid'
        ,height: $(document).height() - $('#collection2Select').offset().top - 75,
        //开启分页
        page: true,
        limits: [300,600,900],
    });

    table.on('tool(collection2Table)', function(obj){
        let data = obj.data;
        //发票编号
        let invoiceNumber = data.invoiceNumber;
        if(obj.event === 'collectionAmount') {
            parent.detab("views/jsp/Money/collection.jsp");
            parent.intab("views/jsp/Money/collection.jsp?billNo="+invoiceNumber, "收款");
        }else if (obj.event === 'invoiceNumber'){
            let billId=null;
            $.ajax({
                url:'billChange/findBillExchangeInfo?invoiceNumber='+invoiceNumber,
                type: 'GET',
                async: false, // 同步
                success: function (re) {
                    billId=re.data.billId;
                }
            })
            parent.detab("views/jsp/ExportBusiness/tpl/viewforeignexchangesettlement.jsp");
            parent.intab("views/jsp/ExportBusiness/tpl/viewforeignexchangesettlement.jsp?id="+billId, "结汇明细");
        }
    });

    //搜索提交
    form.on('submit(submitform)', function(data){
        if(isEmpty(operationList.getValue('valueStr')) && isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptOperationList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
            data.field.operationCode = user.code;
            data.field.salesmanCode = user.code;
        }

        table.reload('maininformationtableid', {
            page: {
                limit:300,
                curr: 1
            },
            url:'receivePayment/collectionStatistics2ListByPage',
            where:  data.field
        }, 'data');
        return false;
    });


    form.on('submit(exportData)', function (queryReq) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"receivePayment/export/getContractStatisticsTwoExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 120,
                        'AH': 120
                    }, 120);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '按发票应收统计价格术语不同.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
    document.getElementById('clear').onclick = function(){
        collectTypeData.setValue([ ]);
        billTypeData.setValue([ ]);
        businessModelList.setValue([ ]);
        operationList.setValue([ ]);
        pricetermList.setValue([ ]);
        salesmanList.setValue([ ]);
        $("#customerCode").val("");
        $("#customerName").val("");
        deptSalesmanList.setValue([ ]);
        deptOperationList.setValue([ ]);
    };

});


